//
//  STTools_IPAPurchaseManger.m
//  togetherPlay
//
//  Created by coder on 2019/1/15.
//  Copyright © 2019 stoneobs.qq.com. All rights reserved.
//

#import "STTools_IPAPurchaseManger.h"


static const char SKPaymentTransactionBaseRecipe = '\29';

@interface STTools_IPAPurchaseManger()
<
SKPaymentTransactionObserver,
SKProductsRequestDelegate
>
@property(nonatomic, strong) NSString                                           *userId;/**< 用户id */
@property(nonatomic, strong) UIView                                            *loadingView;/**< 加载 */
@property(nonatomic, copy) STIPAPurchaseInput_stoneobs_handle                     handle;/**< 支付回调 */
@property(nonatomic, strong)  SKPaymentTransaction               *currentTransaction                  ;/**<   */
@property(nonatomic, strong) NSString                     *currentRecipString;/**<  */
@end
@implementation STTools_IPAPurchaseManger
+ (STTools_IPAPurchaseManger*)manger{
    static STTools_IPAPurchaseManger * defult = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defult = [STTools_IPAPurchaseManger new];
    });
    return defult;
}
- (NSMutableArray<STTools_IPAPurchaseModel *> *)productListArray{
    if (!_productListArray) {

    }
    return _productListArray;
}
- (void)stoneobs_fun_st_beginMonitorWithUserID:(NSString *)userId{
    if (!userId.length) {
         NSAssert(NO,@"userId 不可以为空");
    }
    self.userId = userId;
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
#pragma mark --Public Method
- (void)stoneobs_fun_st_beginBuyWithProductId:(NSString *)productId handle:(nonnull STIPAPurchaseInput_stoneobs_handle)handle{
    if (!self.userId.length) {
        NSAssert(NO,@"userId 还未赋值");
    }
    if (!productId.length) {
        NSAssert(NO,@"productId 还未赋值");
    }
    if([SKPaymentQueue canMakePayments]) {
        DDLogInfo(@"允许程序内付费购买");
    }else{
        DDLogInfo(@"不允许程序内付费购买");
        NSAssert(NO,@"不允许程序内付费购买");
    }

    NSArray * stoneobs_temp_product = @[productId];
    NSSet   *stoneobs_temp_nsset = [NSSet setWithArray:stoneobs_temp_product];
    SKProductsRequest * stoneobs_temp_request= [[SKProductsRequest alloc] initWithProductIdentifiers:stoneobs_temp_nsset];
    stoneobs_temp_request.delegate = self;
    [stoneobs_temp_request start];
    [self showLoadingView];
    self.handle = handle;
    
}
- (void)stoneobs_fun_st_makeOrderCompleteWithReceiptString:(NSString *)receiptString{
    if (receiptString.length) {
        if ([self.currentRecipString isEqualToString:receiptString]) {
            [[SKPaymentQueue defaultQueue] finishTransaction:self.currentTransaction];
            self.currentTransaction = nil;
            self.currentRecipString = nil;
            return;
        }
        //从现有模型中 找出这个 订单
        NSMutableArray * dealArray = NSMutableArray.new;
        for (STTools_IPAPurchaseModel * model in self.currentUnusualArray) {
            if ([model.receiptString isEqualToString:receiptString]) {
                [[SKPaymentQueue defaultQueue] finishTransaction:model.transaction];
            }else{
                [dealArray addObject:model];
            }
        }
        _currentUnusualArray =  dealArray;
        
    }
}
#pragma mark --subView
- (void)showLoadingView{
    [self.loadingView removeFromSuperview];
    UIWindow * stoneobs_temp_window = UIApplication.sharedApplication.delegate.window;
    UIView * stoneobs_temp_contentView = [[UIView alloc] initWithFrame:stoneobs_temp_window.bounds];
    [stoneobs_temp_window addSubview:stoneobs_temp_contentView];
    self.loadingView = stoneobs_temp_contentView;
    
    UIActivityIndicatorView * stoneobs_temp_juhuaView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [stoneobs_temp_juhuaView startAnimating];
    UIView * stoneobs_temp_grawView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    stoneobs_temp_juhuaView.center = CGPointMake(stoneobs_temp_grawView.frame.size.width/2, stoneobs_temp_grawView.frame.size.width/2);
    stoneobs_temp_grawView.layer.cornerRadius = 15;
    stoneobs_temp_grawView.center = stoneobs_temp_window.center;
    stoneobs_temp_grawView.backgroundColor = [UIColor grayColor];
    [stoneobs_temp_grawView addSubview:stoneobs_temp_juhuaView];
    [stoneobs_temp_contentView addSubview:stoneobs_temp_grawView];
}
#pragma mark --SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response{
    NSLog(@"-----------收到产品反馈信息--------------");
    NSArray*myProduct = response.products;
    NSLog(@"产品Product ID:%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量: %d", (int)[myProduct count]);// populate UI
    if (myProduct.count == 0) {
        NSLog(@"产品数量为空");
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.loadingView removeFromSuperview];
            if (self.handle) {
                self.handle(NO,@"",@"产品数量为空");
            }
            [SVProgressHUD showErrorWithStatus:@"购买失败"];
        });

        return;
    }
    for(SKProduct*product in myProduct){
        
        NSLog(@"product info");
        NSLog(@"SKProduct 描述信息%@", [product description]);
        NSLog(@"产品标题 %@", product.localizedTitle);
        NSLog(@"产品描述信息: %@", product.localizedDescription);
        NSLog(@"价格: %@", product.price);
        NSLog(@"Product id: %@", product.productIdentifier);
    }
    SKProduct* product = myProduct.firstObject;
    SKMutablePayment *  ment  = [SKMutablePayment paymentWithProduct:myProduct.firstObject];
    NSDictionary * dic = @{
                           @"onwer_id":self.userId,
                           @"productPrice":product.price,
                           @"productId":product.productIdentifier,
                           @"productDesc":product.localizedDescription.length?product.localizedDescription:@"",
                           @"productTitle":product.localizedTitle.length?product.localizedTitle:@"",
                           @"createTime":@(NSDate.date.timeIntervalSince1970).description,
                           };
    //将此次内购和用户绑定
    ment.applicationUsername = dic.mj_JSONString;
    [[SKPaymentQueue defaultQueue] addPayment:ment];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    
    [self.loadingView removeFromSuperview];
    if (self.handle) {
        if (self.handle) {
            self.handle(NO,@"",@"无法查询到商品");
        }
    }
    NSLog(@"无法查询到商品");
}
#pragma mark -- 监听结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    
    //程序响应期间 只响应一次异常订单
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSMutableArray * dealArray = [NSMutableArray new];
        for (SKPaymentTransaction * trance in transactions) {
            NSString * json = trance.payment.applicationUsername;
            STTools_IPAPurchaseModel * model =  STTools_IPAPurchaseModel.new;
            if (json) {
                NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                model = [STTools_IPAPurchaseModel mj_objectWithKeyValues:dic];
                model.transaction = trance;
                NSString * baseRecip = [self getReceipt];
                model.receiptString = baseRecip;
                [dealArray addObject:model];
            }else{
                //全部取消
                [[SKPaymentQueue defaultQueue] finishTransaction:trance];
            }

            
            
        }
        if (!self.handle) {
            _currentUnusualArray = dealArray.copy;
            if (self.unusualHandle) {
                self.unusualHandle(_currentUnusualArray);
                return ;
            }
        }

    });
    //当用户购买的操作有结果时，就会触发下面的回调函数，也会有之前购买成功的回调
    for (SKPaymentTransaction * transaction in transactions) {
        
        switch (transaction.transactionState) {
                
            case SKPaymentTransactionStatePurchased:{
                
                [self completeTransaction:transaction];
                
            }break;
                
            case SKPaymentTransactionStateFailed:{
                
                [self failedTransaction:transaction];
            }break;
                
            case SKPaymentTransactionStateRestored:{//已经购买过该商品
                
                [self restoreTransaction:transaction];
                
            }break;
                
            case SKPaymentTransactionStatePurchasing:{
                
                NSLog(@"正在购买中...");
                
            }break;
                
            case SKPaymentTransactionStateDeferred:{
                
                NSLog(@"最终状态未确定");
                
            }break;
                
            default:
                break;
        }
    }
}
//完成交易
#pragma mark -- 交易完成的回调
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    self.currentTransaction = transaction;
    NSString * json = transaction.payment.applicationUsername;
    STTools_IPAPurchaseModel * model =  STTools_IPAPurchaseModel.new;
    if (json) {
        NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        model = [STTools_IPAPurchaseModel mj_objectWithKeyValues:dic];
//        model.onwer_id;
    }
    [self.loadingView removeFromSuperview];
    NSString * base64String =   [self getReceipt]; //获取交易成功后的购买凭证
    self.currentRecipString = base64String;
    if (self.handle) {
        if (self.handle) {
            self.handle(YES,base64String,@"");
        }
        self.handle = nil;
    }
    
}

#pragma mark -- 处理交易失败回调
- (void)failedTransaction:(SKPaymentTransaction *)transaction
{
    [self.loadingView removeFromSuperview];
    NSString *error = nil;
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
    } else {
         NSLog(@"取消购买");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction{
    
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
}

#pragma mark -- 获取购买凭证
-(NSString*)getReceipt{
    
    NSURL * receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData * receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString * base64String = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSLog(@"购买凭证:%@",base64String);
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", base64String];//拼接请求数据
    return bodyString;
}


@end

@interface STTools_IPAPurchaseModel()

@end
@implementation STTools_IPAPurchaseModel



@end
